<!DOCTYPE html>
<html>
  <!-- Html Head Tag-->
  <head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="cityking">
  <!-- Open Graph Data -->
  <meta property="og:title" content="python requests用法总结"/>
  <meta property="og:description" content="" />
  <meta property="og:site_name" content="python &amp;&amp; django"/>
  <meta property="og:type" content="article" />
  <meta property="og:image" content="https://cityking.github.io/hexo_project"/>
  
    <link rel="alternate" href="/atom.xml" title="python &amp;&amp; django" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  

  <!-- Site Title -->
  <title>python && django</title>

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="/hexo_project/css/bootstrap.min.css">
  <!-- Custom CSS -->
  
  <link rel="stylesheet" href="/hexo_project/css/style.light.css">

  <!-- Google Analytics -->
  

</head>

  <body>
    <!-- Page Header -->


<header class="site-header header-background" style="background-image: url(/hexo_project//img/background.jpg)">
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <div class="page-title with-background-image">
          <p class="title">python requests用法总结</p>
          <p class="subtitle"></p>
        </div>
        <div class="site-menu with-background-image">
          <ul>
            
              <li>
                <a href="/hexo_project/">
                  
                  Home
                  
                </a>
              </li>
            
              <li>
                <a href="/hexo_project/archives">
                  
                  Archives
                  
                </a>
              </li>
            
              <li>
                <a href="https://github.com/cityking">
                  
                  Github
                  
                </a>
              </li>
            
              <li>
                <a href="mailto:<154443603@qq.com>">
                  
                  Email
                  
                </a>
              </li>
            
          </ul>
        </div>
      </div>
    </div>
  </div>
</header>

<article>
  <div class="container typo">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <div class="post-info text-muted">
          
            <!-- Author -->
            <span class="author info">By cityking</span>
          
          <!-- Date -->
          <span class="date-time info">On
            <span class="date">2018-03-02</span>
            <span class="time">18:03:36</span>
          </span>
          
          <!--  Categories  -->
            <span class="categories info">Under 

<a href="/hexo_project/categories/python/">python</a>
</span>
          
        </div>
        <!-- Tags -->
        
          <div class="post-tags text-muted">
            Tags: 

<a class="tag" href="/hexo_project/tags/python/">#python</a> <a class="tag" href="/hexo_project/tags/requests/">#requests</a>


          </div>
        
        <!-- Post Main Content -->
        <div class="post-content">
          <p>requests是一个很实用的Python HTTP客户端库，编写爬虫和测试服务器响应数据时经常会用到<br><a id="more"></a><br><a href="http://docs.python-requests.org/en/master/" target="_blank" rel="noopener">官方网址：http://docs.python-requests.org/en/master/</a></p>
<p>安装方式一般采用$ pip install requests</p>
<h1 id="GET请求"><a href="#GET请求" class="headerlink" title="GET请求"></a>GET请求</h1><p><code>r  = requests.get(&#39;http://httpbin.org/get&#39;)</code><br>传参<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">payload = &#123;&apos;key1&apos;: &apos;value1&apos;, &apos;key2&apos;: &apos;value2&apos;, &apos;key3&apos;: None&#125;</span><br><span class="line">r = requests.get(&apos;http://httpbin.org/get&apos;, params=payload)</span><br></pre></td></tr></table></figure></p>
<p>请求会转化成下面的url访问<br><code>http://httpbin.org/get?key2=value2&amp;key1=value1</code><br>字典中值为None的键不会添加到查询字符串中</p>
<p>参数也可以传递列表<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; payload = &#123;&apos;key1&apos;: &apos;value1&apos;, &apos;key2&apos;: [&apos;value2&apos;, &apos;value3&apos;]&#125;</span><br><span class="line"></span><br><span class="line">&gt;&gt;&gt; r = requests.get(&apos;http://httpbin.org/get&apos;, params=payload)</span><br><span class="line">&gt;&gt;&gt; print(r.url)</span><br><span class="line">	http://httpbin.org/get?key1=value1&amp;key2=value2&amp;key2=value3</span><br></pre></td></tr></table></figure></p>
<p>r.text 返回headers中的编码解析的结果，可以通过r.encoding = ‘gbk’来变更解码方式<br>r.content返回二进制结果<br>r.json()返回JSON格式，可能抛出异常<br>r.status_code<br>r.raw返回原始socket respons，需要加参数stream=True</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; r = requests.get(&apos;https://api.github.com/events&apos;, stream=True)</span><br><span class="line">&gt;&gt;&gt; r.raw</span><br><span class="line">&lt;requests.packages.urllib3.response.HTTPResponse object at 0x101194810&gt;</span><br><span class="line">&gt;&gt;&gt; r.raw.read(10)</span><br><span class="line">	&apos;\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03&apos;</span><br></pre></td></tr></table></figure>
<p>将结果保存到文件，利用r.iter_content()<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">with open(filename, &apos;wb&apos;) as fd:</span><br><span class="line">    for chunk in r.iter_content(chunk_size):</span><br><span class="line">        fd.write(chunk)</span><br></pre></td></tr></table></figure></p>
<p>传递headers<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; headers = &#123;&apos;user-agent&apos;: &apos;my-app/0.0.1&apos;&#125;</span><br><span class="line">&gt;&gt;&gt; r = requests.get(url, headers=headers)</span><br></pre></td></tr></table></figure></p>
<p>传递cookies<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; url = &apos;http://httpbin.org/cookies&apos;</span><br><span class="line">&gt;&gt;&gt; r = requests.get(url, cookies=dict(cookies_are=&apos;working&apos;))</span><br><span class="line">&gt;&gt;&gt; r.text</span><br><span class="line">&apos;&#123;&quot;cookies&quot;: &#123;&quot;cookies_are&quot;: &quot;working&quot;&#125;&#125;&apos;</span><br></pre></td></tr></table></figure></p>
<h1 id="POST请求"><a href="#POST请求" class="headerlink" title="POST请求"></a>POST请求</h1><p>传递表单<br><code>r = requests.post(&#39;http://httpbin.org/post&#39;, data = {&#39;key&#39;:&#39;value&#39;})</code><br>通常，你想要发送一些表单形式的数据—就像一个HTML表单。 要实现这个，只需简单地传递一个字典给 data 参数:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; payload = &#123;&apos;key1&apos;: &apos;value1&apos;, &apos;key2&apos;: &apos;value2&apos;&#125;</span><br><span class="line">&gt;&gt;&gt; r = requests.post(&quot;http://httpbin.org/post&quot;, data=payload)</span><br></pre></td></tr></table></figure></p>
<p>传递json<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; url = &apos;https://api.github.com/some/endpoint&apos;</span><br><span class="line">&gt;&gt;&gt; payload = &#123;&apos;some&apos;: &apos;data&apos;&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; r = requests.post(url, data=json.dumps(payload))</span><br></pre></td></tr></table></figure>
<p>或者<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; r = requests.post(url, json=payload)</span><br></pre></td></tr></table></figure></p>
<p>传递文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">url = &apos;http://httpbin.org/post&apos;</span><br><span class="line">&gt;&gt;&gt; files = &#123;&apos;file&apos;: open(&apos;report.xls&apos;, &apos;rb&apos;)&#125;</span><br><span class="line">&gt;&gt;&gt; r = requests.post(url, files=files)</span><br></pre></td></tr></table></figure></p>
<p>配置files，filename, content_type and headers<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">files = &#123;&apos;file&apos;: (&apos;report.xls&apos;, open(&apos;report.xls&apos;, &apos;rb&apos;), &apos;application/vnd.ms-excel&apos;, &#123;&apos;Expires&apos;: &apos;0&apos;&#125;)&#125;</span><br><span class="line">files = &#123;&apos;file&apos;: (&apos;report.csv&apos;, &apos;some,data,to,send\nanother,row,to,send\n&apos;)&#125;</span><br></pre></td></tr></table></figure></p>
<p>超时设置<br><code>requests.get(&#39;http://github.com&#39;, timeout=0.001)</code></p>
<h1 id="高级特性"><a href="#高级特性" class="headerlink" title="高级特性"></a>高级特性</h1><p><a href="http://docs.python-requests.org/en/master/user/advanced/#advanced" target="_blank" rel="noopener">官方网址 http://docs.python-requests.org/en/master/user/advanced/#advanced</a></p>
<h2 id="session"><a href="#session" class="headerlink" title="session"></a>session</h2><p>自动保存cookies，可以设置请求参数，下次请求自动带上请求参数<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">s = requests.Session()</span><br><span class="line">s.get(&apos;http://httpbin.org/cookies/set/sessioncookie/123456789&apos;)</span><br><span class="line">r = s.get(&apos;http://httpbin.org/cookies&apos;)</span><br><span class="line">print(r.text)</span><br><span class="line"># &apos;&#123;&quot;cookies&quot;: &#123;&quot;sessioncookie&quot;: &quot;123456789&quot;&#125;&#125;&apos;</span><br></pre></td></tr></table></figure></p>
<p>session可以用来提供默认数据，函数参数级别的数据会和session级别的数据合并，如果key重复，函数参数级别的数据将覆盖session级别的数据。如果想取消session的某个参数，可以在传递一个相同key，value为None的dict<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">s = requests.Session()</span><br><span class="line">s.auth = (&apos;user&apos;, &apos;pass&apos;) #权限认证</span><br><span class="line">s.headers.update(&#123;&apos;x-test&apos;: &apos;true&apos;&#125;)</span><br><span class="line"># both &apos;x-test&apos; and &apos;x-test2&apos; are sent</span><br><span class="line">s.get(&apos;http://httpbin.org/headers&apos;, headers=&#123;&apos;x-test2&apos;: &apos;true&apos;&#125;)</span><br></pre></td></tr></table></figure></p>
<p>函数参数中的数据只会使用一次，并不会保存到session中</p>
<p>如：cookies仅本次有效<br><code>r = s.get(&#39;http://httpbin.org/cookies&#39;, cookies={&#39;from-my&#39;: &#39;browser&#39;})</code></p>
<p>session也可以自动关闭<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">with requests.Session() as s:</span><br><span class="line">    s.get(&apos;http://httpbin.org/cookies/set/sessioncookie/123456789&apos;)</span><br></pre></td></tr></table></figure></p>
<p>响应结果不仅包含响应的全部信息，也包含请求信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">r = requests.get(&apos;http://en.wikipedia.org/wiki/Monty_Python&apos;)</span><br><span class="line">r.headers</span><br><span class="line">r.request.headers</span><br></pre></td></tr></table></figure>
<h2 id="SSL证书验证"><a href="#SSL证书验证" class="headerlink" title="SSL证书验证"></a>SSL证书验证</h2><p>Requests可以为HTTPS请求验证SSL证书，就像web浏览器一样。要想检查某个主机的SSL证书，你可以使用 verify 参数:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;https://kennethreitz.com&apos;, verify=True)</span><br><span class="line">requests.exceptions.SSLError: hostname &apos;kennethreitz.com&apos; doesn&apos;t match either of &apos;*.herokuapp.com&apos;, &apos;herokuapp.com&apos;</span><br></pre></td></tr></table></figure>
<p>在该域名上我没有设置SSL，所以失败了。但Github设置了SSL:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;https://github.com&apos;, verify=True)</span><br><span class="line">&lt;Response [200]&gt;</span><br></pre></td></tr></table></figure></p>
<p>对于私有证书，你也可以传递一个CA_BUNDLE文件的路径给 verify 。你也可以设置REQUEST_CA_BUNDLE 环境变量。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;https://github.com&apos;, verify=&apos;/path/to/certfile&apos;)</span><br></pre></td></tr></table></figure></p>
<p>如果你将 verify 设置为False，Requests也能忽略对SSL证书的验证。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;https://kennethreitz.com&apos;, verify=False)</span><br><span class="line">&lt;Response [200]&gt;</span><br></pre></td></tr></table></figure></p>
<p>默认情况下， verify 是设置为True的。选项 verify 仅应用于主机证书。</p>
<p>你也可以指定一个本地证书用作客户端证书，可以是单个文件（包含密钥和证书）或一个包含两个文件路径的元组:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;https://kennethreitz.com&apos;, cert=(&apos;/path/server.crt&apos;, &apos;/path/key&apos;))</span><br><span class="line">&lt;Response [200]&gt;</span><br></pre></td></tr></table></figure></p>
<h2 id="响应体内容工作流"><a href="#响应体内容工作流" class="headerlink" title="响应体内容工作流"></a>响应体内容工作流</h2><p>默认情况下，当你进行网络请求后，响应体会立即被下载。你可以通过 stream 参数覆盖这个行为，推迟下载响应体直到访问 Response.content 属性:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">tarball_url = &apos;https://github.com/kennethreitz/requests/tarball/master&apos;</span><br><span class="line">r = requests.get(tarball_url, stream=True)</span><br></pre></td></tr></table></figure></p>
<p>此时仅有响应头被下载下来了，连接保持打开状态，因此允许我们根据条件获取内容:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">if int(r.headers[&apos;content-length&apos;]) &lt; TOO_LONG:</span><br><span class="line">  content = r.content</span><br><span class="line">  ...</span><br></pre></td></tr></table></figure></p>
<p>如果设置stream为True，请求连接不会被关闭，除非读取所有数据或者调用Response.close。<br>可以使用contextlib.closing来自动关闭连接：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">import requests</span><br><span class="line">from contextlib</span><br><span class="line">import closing</span><br><span class="line"></span><br><span class="line">tarball_url = &apos;https://github.com/kennethreitz/requests/tarball/master&apos;</span><br><span class="line">file = r&apos;D:\Documents\WorkSpace\Python\Test\Python34Test\test.tar.gz&apos;</span><br><span class="line">with closing(requests.get(tarball_url, stream=True)) as r:</span><br><span class="line">	with open(file, &apos;wb&apos;) as f:</span><br><span class="line">		for data in r.iter_content(1024):</span><br><span class="line">			f.write(data)</span><br></pre></td></tr></table></figure>
<h2 id="Keep-Alive"><a href="#Keep-Alive" class="headerlink" title="Keep-Alive"></a>Keep-Alive</h2><p><a href="http://docs.python-requests.org/en/master/user/advanced/" target="_blank" rel="noopener">官方网址 http://docs.python-requests.org/en/master/user/advanced/</a><br>同一会话内你发出的任何请求都会自动复用恰当的连接！<br>注意：只有所有的响应体数据被读取完毕连接才会被释放为连接池；所以确保将 stream设置为 False 或读取 Response 对象的 content 属性。</p>
<h2 id="流式上传"><a href="#流式上传" class="headerlink" title="流式上传"></a>流式上传</h2><p>Requests支持流式上传，这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传，仅需为你的请求体提供一个类文件对象即可:<br>读取文件请使用字节的方式，这样Requests会生成正确的Content-Length</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">with open(&apos;massive-body&apos;, &apos;rb&apos;) as f:</span><br><span class="line">    requests.post(&apos;http://some.url/streamed&apos;, data=f)</span><br></pre></td></tr></table></figure>
<h2 id="分块传输编码"><a href="#分块传输编码" class="headerlink" title="分块传输编码"></a>分块传输编码</h2><p>对于出去和进来的请求，Requests也支持分块传输编码。要发送一个块编码的请求，仅需为你的请求体提供一个生成器<br>注意生成器输出应该为bytes</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">def gen():</span><br><span class="line">    yield b&apos;hi&apos;</span><br><span class="line">    yield b&apos;there&apos;</span><br><span class="line"></span><br><span class="line">requests.post(&apos;http://some.url/chunked&apos;, data=gen())</span><br></pre></td></tr></table></figure>
<h2 id="多文件上传"><a href="#多文件上传" class="headerlink" title="多文件上传"></a>多文件上传</h2><p><a href="http://docs.python-requests.org/en/master/user/advanced/" target="_blank" rel="noopener">官方网址 http://docs.python-requests.org/en/master/user/advanced/</a></p>
<p>html表示为<br><code>&lt;input type=&quot;file&quot; name=&quot;images&quot; multiple=&quot;true&quot; required=&quot;true&quot;/</code></p>
<p>设置文件列表</p>
<p>单个文件格式 (form_field_name, file_info):<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; url = &apos;http://httpbin.org/post&apos;</span><br><span class="line">&gt;&gt;&gt; multiple_files = [</span><br><span class="line">        (&apos;images&apos;, (&apos;foo.png&apos;, open(&apos;foo.png&apos;, &apos;rb&apos;), &apos;image/png&apos;)),</span><br><span class="line">        (&apos;images&apos;, (&apos;bar.png&apos;, open(&apos;bar.png&apos;, &apos;rb&apos;), &apos;image/png&apos;))]</span><br><span class="line">&gt;&gt;&gt; r = requests.post(url, files=multiple_files)</span><br><span class="line">&gt;&gt;&gt; r.text</span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  &apos;files&apos;: &#123;&apos;images&apos;: &apos; ....&apos;&#125;</span><br><span class="line">  &apos;Content-Type&apos;: &apos;multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a&apos;,</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>Custom Authentication</p>
<h2 id="自定义验证机制"><a href="#自定义验证机制" class="headerlink" title="自定义验证机制"></a>自定义验证机制</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">from requests.auth import AuthBase</span><br><span class="line"></span><br><span class="line">class PizzaAuth(AuthBase):</span><br><span class="line">    &quot;&quot;&quot;Attaches HTTP Pizza Authentication to the given Request object.&quot;&quot;&quot;</span><br><span class="line">    def __init__(self, username):</span><br><span class="line">        # setup any auth-related data here</span><br><span class="line">        self.username = username</span><br><span class="line"></span><br><span class="line">def __call__(self, r):</span><br><span class="line">        # modify and return the request</span><br><span class="line">        r.headers[&apos;X-Pizza&apos;] = self.username</span><br><span class="line">        return r</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; requests.get(&apos;http://pizzabin.org/admin&apos;, auth=PizzaAuth(&apos;kenneth&apos;))</span><br><span class="line">&lt;Response [200]&gt;</span><br></pre></td></tr></table></figure>
<p><a href="http://docs.python-requests.org/en/master/user/advanced/" target="_blank" rel="noopener">官方网址 http://docs.python-requests.org/en/master/user/advanced/</a></p>
<h2 id="流式请求"><a href="#流式请求" class="headerlink" title="流式请求"></a>流式请求</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">r = requests.get(&apos;http://httpbin.org/stream/20&apos;, stream=True)</span><br><span class="line">for line in r.iter_lines():</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure>
<h2 id="代理"><a href="#代理" class="headerlink" title="代理"></a>代理</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">import requests</span><br><span class="line"></span><br><span class="line">proxies = &#123;</span><br><span class="line">  &apos;http&apos;: &apos;http://10.10.1.10:3128&apos;,</span><br><span class="line">  &apos;https&apos;: &apos;http://10.10.1.10:1080&apos;,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">requests.get(&apos;http://example.org&apos;, proxies=proxies)</span><br></pre></td></tr></table></figure>
<p>含有用户密码的代理<br><code>proxies = {&#39;http&#39;: &#39;http://user:pass@10.10.1.10:3128/&#39;}</code></p>
<p>超时</p>
<p>设置单个值时，这个值将同时应用于连接超时和读取超时<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r = requests.get(&apos;https://github.com&apos;, timeout=5)</span><br></pre></td></tr></table></figure></p>
<p>也可传一对数据分开设置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r = requests.get(&apos;https://github.com&apos;, timeout=(3.05, 27))</span><br></pre></td></tr></table></figure></p>
<p>如果服务器非常慢，可以把超时时间设为None<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r = requests.get(&apos;https://github.com&apos;, timeout=None)</span><br></pre></td></tr></table></figure></p>

        </div>
      </div>
    </div>
  </div>
</article>



    <!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <p class="copyright text-muted">
          Theme By <a target="_blank" href="https://github.com/levblanc">Levblanc.</a>
          Inspired By <a target="_blank" href="https://github.com/klugjo/hexo-theme-clean-blog">Clean Blog.</a>
        <p class="copyright text-muted">
          Powered By <a target="_blank" href="https://hexo.io/">Hexo.</a>
        </p>
      </div>
    </div>
  </div>
</footer>


    <!-- After Footer Scripts -->
<script src="/hexo_project/js/highlight.pack.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", function(event) {
    var codeBlocks = Array.prototype.slice.call(document.getElementsByTagName('pre'))
    codeBlocks.forEach(function(block, index) {
      hljs.highlightBlock(block);
    });
  });
</script>

  </body>
</html>

